package com.xmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.xmall.bean.table.Footprint;
import com.xmall.bean.table.FootprintExample;
import com.xmall.bean.table.Goods;
import com.xmall.bean.table.User;
import com.xmall.bean.vo.FootprintDataVO;
import com.xmall.bean.vo.FootprintVO;
import com.xmall.mapper.FootprintMapper;
import com.xmall.mapper.GoodsMapper;
import com.xmall.mapper.UserMapper;
import com.xmall.service.FootprintService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Connor
 * @ClassName: FootprintServiceImpl
 * @PackageName: com.xmall.service.impl
 * @date 2020/12/08
 * @Version 1.0
 */
@Service
public class FootprintServiceImpl implements FootprintService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public FootprintVO<FootprintDataVO> listFootprint(Integer page, Integer size) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer totalRecord = footprintMapper.queryTotalFootprint(user.getId());

        PageHelper.startPage(page, size);
        FootprintExample example = new FootprintExample();
        FootprintExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andDeletedEqualTo(false);

        List<FootprintDataVO> footprintDataVOS = new ArrayList<>();
        List<Footprint> footprintList = footprintMapper.selectByExample(example);
        // TODO 考虑自己写查询语句，因为只需要goods_id和id两个字段，这样做可缓解数据库查询压力，SQL优化
        for (Footprint footprint : footprintList) {
            Goods goods = goodsMapper.selectByPrimaryKey(footprint.getGoodsId());
            footprintDataVOS.add(new FootprintDataVO(goods.getBrief(),
                    goods.getPicUrl(),
                    goods.getAddTime(),
                    footprint.getGoodsId(),
                    goods.getName(),
                    footprint.getId(),
                    goods.getRetailPrice()));
        }
        return new FootprintVO(totalRecord % size == 0 ? totalRecord / size : totalRecord / size + 1, footprintDataVOS);
    }

    @Override
    public void deleteFootprint(Map<String, Integer> map) {
        footprintMapper.updateByPrimaryKeySelective(
                new Footprint(map.get("id"),null,null,null,null,true));
    }
}
